//
//  APIService.swift
//  Box
//
//  Created by mn on 2025/4/1.
//
import Moya
struct APIResponse : Codable {
    let success: Bool
    let message: String
    let code: Int
    let timestamp: Int
}
struct APIService {
    static private let provider = MoyaProvider<API>()

    static func request(api: API, completion: @escaping (APIResponse,String?) -> Void) {
        debugPrint("Requesting: \(api.method.rawValue) \(api.baseURL)\(api.path)")
        
        switch api.task {
        case .requestParameters(let parameters, _):
            debugPrint("Parameters: \(parameters)")
        default:
            debugPrint("No parameters")
        }
        
        provider.request(api) { result in
            switch result {
            case .success(let response):
                if let responseString = String(data: response.data, encoding: .utf8){
                    debugPrint(responseString)

                    do {
                        let apiResponse = try JSONDecoder().decode(APIResponse.self, from: response.data)
                        completion(apiResponse,responseString)
                    } catch {
                        let errorResponse = APIResponse(success: false, message: "JSON解析失败", code: -1, timestamp: 0)
                        completion(errorResponse,nil)
                    }
                }
                
            case .failure(let error):
                debugPrint("Request failed: \(error.localizedDescription)")
                let errorResponse = APIResponse(success: false, message: error.localizedDescription, code: -1, timestamp: 0)
                completion(errorResponse,nil)
            }
        }
    }
}
